/*
 * @Date: 2024-06-23 17:36:57
 */

const request = require('sync-request');
const CryptoJS = require('crypto-js');
module.exports = class {
    AES_KEY = 'greenh5java12345' // 密钥, 需16个字符
    AES_IV = 'greenh5java12345' // 密钥偏移量，16个字符
    key = CryptoJS.enc.Utf8.parse(this.AES_KEY);
    iv = CryptoJS.enc.Utf8.parse(this.AES_IV);
    host = "ygmcapi.yiyutx.top";
    timer = 0;
    encrypt(data) {
        const srcs = CryptoJS.enc.Utf8.parse(data)
        const encrypted = CryptoJS.AES.encrypt(srcs, this.key, {
            iv: this.iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        })
        return encrypted.toString()
    }

    decrypt(data) {
        const decrypted = CryptoJS.AES.decrypt(data, this.key, {
            iv: this.iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        })
        return CryptoJS.enc.Utf8.stringify(decrypted)
            .toString()
    }

    post(url, data) {
        if (new Date().getTime() - this.timer < 500) this.sleep((new Date().getTime()) - this.timer);
        data.checkTime = new Date()
            .getTime()
        var text = this.encrypt(JSON.stringify(data, true));
        const response = request('POST', url, {
            'headers': {
                'Content-Type': 'application/json; charset=utf-8',
                'Connection': 'Keep-Alive',
                // 'user-agent': user.agent
            },
            'body': text
        })
        var body = response.getBody()
            .toString();
        if (response.statusCode != 200) {
            console.error("访问出现错误！")
            console.error("text:" + text)
            console.error("decrypt:" + this.decrypt(text))
            console.error(response)
            console.error(body)
            console.error("访问出错！！！")
            return false;
        }
        body = JSON.parse(body, true);
        if (body.code != 200) {
            console.error("访问出现错误！")
            console.error("text:" + text)
            console.error("decrypt:" + this.decrypt(text))
            console.error(response)
            console.error(body)
            console.error("访问出错！！！")
            return false;
        }
        return body.data
    }
    sleep(n) {
        Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n);
    }
}